using FrameworkDesign;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public interface IItemSystme : ISystem
{
    IItem SelectedItemModel(string key);
    //List<Slot> mBagSlots { get; }
    //List<Slot> mSlots { get; }
    bool AddItem(string key, string slotGroupName, int addCount = 1);
    bool SubItem(string key, string slotGroupName, int subCount = 1);
    Slot currentEntreSlot { get; set; }
    Dictionary<string, SlotGroup> SlotGroupDic { get; }
    
}
public class ItemSystem : AbstractSystem, IItemSystme
{

    private Dictionary<string, IItem> mItems = new Dictionary<string, IItem>();

    public Dictionary<string, SlotGroup> SlotGroupDic { get; } = new Dictionary<string, SlotGroup>();

    private Func<Slot, bool> CanAdd;
    public Slot currentEntreSlot { get; set; }
    private int slotPoolSize = 3;
    private int bagPoolSize = 10;
    private int equipmentPoolSize = 1;



    public override void OnInit()
    {
        var constModel = this.GetModel<IConstModel>();
        var items = Resources.LoadAll<ItemConfig>("");

        foreach (var item in items)
        {
            mItems[item.GetKey] = item;
        }
        var slots1 = new SlotGroup(slotPoolSize) ;
        var slots2 = new SlotGroup(bagPoolSize);
        var slots3 = new SlotGroup(equipmentPoolSize).WriteCondition(e => e.GetEquipmentType == Equipment.Weapon);


        SlotGroupDic.Add(constModel.GetItemSlotGroupName, slots1);
        SlotGroupDic.Add(constModel.GetBagSlotGroupName, slots2);
        SlotGroupDic.Add(constModel.GetEquipmentSlotGroupName, slots3);
    }

    public IItem SelectedItemModel(string key)
    {
        if (mItems.ContainsKey(key))
        {
            return mItems[key];
        }
        return null;
    }
    private Slot FindAddableSolt(string key, string slotGroupName)
    {
        var mSlots = SlotGroupDic[slotGroupName].Slots;
        Slot slot = null;
        slot = mSlots.Find(e => e.Item.mValue?.GetKey == key);
        if (slot != null)
        {
            return slot;
        }
        slot = mSlots.Find(e => e.Count.mValue == 0);
        if (slot != null)
        {
            slot.Item.mValue = SelectedItemModel(key);
            return slot;
        }
        return slot;
    }
    public bool AddItem(string key, string slotGroupName, int addCount = 1)
    {

        var slot = FindAddableSolt(key, slotGroupName);
        if (slot != null)
        {
            slot.Count.mValue += addCount;
            return true;
        }
        return false;
    }
    public bool SubItem(string key, string slotGroupName, int subCount = 1)
    {
        var mSlots = SlotGroupDic[slotGroupName].Slots;
        var slot = mSlots.Find(e => e.Item.mValue?.GetKey == key);
        if (slot.Item != null | slot.Count.mValue - subCount > 0)
        {
            slot.Count.mValue -= subCount;
            return true;
        }
        return false;
    }


}
